package com.ly.blog_third.mq;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ly.blog_common.entity.mq.EmailMqInfo;
import com.ly.blog_third.config.MQEmailConfig;
import com.ly.blog_third.email.EmailManagerService;
import com.ly.blog_third.entity.EmailRecordEntity;
import com.ly.blog_third.entity.EmailTemplateEntity;
import com.ly.blog_third.service.EmailRecordService;
import com.ly.blog_third.service.EmailTemplateService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;
import java.util.Map;

/**
 * 邮箱接收处理
 * @author ly create at 2021/6/29 - 12:30
 **/

@Component
public class MqEmailReceiver {

    @Autowired
    private EmailManagerService emailManagerService;

    @Autowired
    private EmailRecordService emailRecordService;

    @Autowired
    private EmailTemplateService emailTemplateService;

    private final String NAME = "Young@你博客系统";
    private final String SIMPLE_SAY = "嘿，为何不留点什么呢！";
    private final String DESC = "yunglee博客系统，一个简单生活小网站，分享生活技术，网络兴趣。有兴致可以自己写写，无兴致可以网上瞅瞅别人的，做一个搬运工（支持网页抓取数据） -_- ";

    /**
     * 开始监听并发送注册邮件信息
     * @param emailMqInfo
     */
    @RabbitHandler
    @RabbitListener(queues = MQEmailConfig.QUEUE_EMAIL)
    public void sendRegisterEmail(EmailMqInfo emailMqInfo) {

        EmailRecordEntity emailRecordEntity = new EmailRecordEntity();
        try {
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("type",emailMqInfo.getType());
            EmailTemplateEntity templateEntity = emailTemplateService.getOne(queryWrapper);
            String sub = templateEntity.getTitle();
            Map<String, String> param = emailMqInfo.getParam();
            String content = replaceData(templateEntity.getTemplate(), param);

            emailRecordEntity.setContent(content);
            emailRecordEntity.setToEmail(Arrays.toString(emailMqInfo.getEmail()));
            emailRecordEntity.setType(emailMqInfo.getType());
            emailManagerService.sendEmail(sub,content,true,null,emailMqInfo.getEmail());
            emailRecordEntity.setIsSuccess(0);
        }catch (Exception e){
            emailRecordEntity.setIsSuccess(1);
        }
        emailRecordEntity.setCreateTime(new Date());
        emailRecordEntity.setLastUpdateTime(new Date());
        emailRecordService.save(emailRecordEntity);
    }

    /**
     * 模板增加参数值匹配
     * @param template
     * @param param
     * @return
     */
    private String replaceData(String template, Map<String,String> param) {

        for (Map.Entry<String,String> entry:param.entrySet()) {
            String key = "#{"+entry.getKey()+"}";
            template = template.replace(key,entry.getValue());
        }
        return template;

    }

}
